
var http = require("http");
var express = require("express"); //引入express
var socketIo = require("socket.io"); //引入socket.io


var app = new express();

app.use('/static', express.static('public'));

var server = http.createServer(app);

var io = new socketIo(server); //将socket.io注入express模块


app.get("/msg", function (req, res, next) {
    res.sendFile(__dirname + "/views/msg.html");
});

app.get("/msg_01", function (req, res, next) {
    res.sendFile(__dirname + "/views/msg_01.html");
});

app.get("/msg_02", function (req, res, next) {
    res.sendFile(__dirname + "/views/msg_02.html");
});

app.get("/msg_03", function (req, res, next) {
    res.sendFile(__dirname + "/views/msg_03.html");
});

server.listen(8888, function () {
    console.log('服务端启动成功！端口8888! http://localhost:8888/msg_01');
}); //express 监听 8080 端口，因为本机80端口已被暂用


var allsocket = {};
var userSokcetMap = {};

//每个客户端socket连接时都会触发 connection 事件
io.of('/one').on("connection", function (clientSocket) {

    var uuid = clientSocket.handshake.query['uuid'] || '';

    var the_id = clientSocket.id;
    allsocket[the_id] = clientSocket;
    userSokcetMap[uuid] = {
        socketId: the_id,
        socket: clientSocket
    };

    console.log(uuid, "========uuid===========");
    console.log(the_id, "========the_id=========");

    //监听客户端发送的 sendMsg 事件
    clientSocket.on("sendMsg", function (data) {
        // data 为客户端发送的消息，可以是 字符串，json对象或buffer

        console.log(clientSocket.id, "========clientSocket.id===========")

        // 使用 emit 发送消息，broadcast 表示 除自己以外的所有已连接的socket客户端。
        // clientSocket.broadcast.emit("receiveMsg", data);
        console.log(data, "=======sendMsg==========");
        // clientSocket.broadcast.emit("receiveMsg", data);
        // clientSocket.emit("receiveMsg", data);

        var toUuid = data.uuid;
        console.log(toUuid, "========toUuid===========");
        console.log(userSokcetMap, "========userSokcetMap===========");

        if (toUuid == "all") {
            console.log("========all===========");
            clientSocket.broadcast.emit("receiveMsg", data);
            clientSocket.emit("receiveMsg", data);
        } else {
            console.log("========某个===========");
            var toSocket = userSokcetMap[toUuid] || null;
            if (toSocket != null) {
                userSokcetMap[toUuid].socket.emit('receiveMsg', data);
            }
        }

    });

});

io.of('/two').on("connection", function (clientSocket) {

    console.log(clientSocket, "=======clientSocket=========")

    //监听客户端发送的 sendMsg 事件
    clientSocket.on("sendMsg", function (data) {
        // data 为客户端发送的消息，可以是 字符串，json对象或buffer

        // 使用 emit 发送消息，broadcast 表示 除自己以外的所有已连接的socket客户端。
        clientSocket.broadcast.emit("receiveMsg", data);
        console.log(data, "=======sendMsg==========");
        //io.sockets.emit("receiveMsg", data);
    });

});